package com.risk.management.controller;

import com.risk.management.dto.Result;
import com.risk.management.entity.Project;
import com.risk.management.entity.Risk;
import com.risk.management.entity.User;
import com.risk.management.service.ProjectService;
import com.risk.management.service.RiskService;
import com.risk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
// 恢复Spring Security依赖
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 风险控制器
 */
@Controller
@RequestMapping("/risk")
public class RiskController {

    @Autowired
    private RiskService riskService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private UserService userService;

    /**
     * 风险列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Risk> risks = riskService.getAllRisks();
        
        // 为每个风险添加项目名称和责任人名称
        for (Risk risk : risks) {
            // 添加项目名称
            if (risk.getProjectId() != null) {
                Project project = projectService.getProjectById(risk.getProjectId());
                if (project != null) {
                    // 使用反射设置动态属性
                    try {
                        java.lang.reflect.Field projectNameField = risk.getClass().getDeclaredField("projectName");
                        projectNameField.setAccessible(true);
                        projectNameField.set(risk, project.getName());
                    } catch (Exception e) {
                        // 如果反射失败，尝试使用model添加
                        model.addAttribute("projectName_" + risk.getId(), project.getName());
                    }
                }
            }
            
            // 添加责任人名称
            if (risk.getOwnerId() != null) {
                User owner = userService.getUserById(risk.getOwnerId());
                if (owner != null) {
                    // 使用反射设置动态属性
                    try {
                        java.lang.reflect.Field ownerNameField = risk.getClass().getDeclaredField("ownerName");
                        ownerNameField.setAccessible(true);
                        ownerNameField.set(risk, owner.getRealName());
                    } catch (Exception e) {
                        // 如果反射失败，尝试使用model添加
                        model.addAttribute("ownerName_" + risk.getId(), owner.getRealName());
                    }
                }
            }
        }
        
        model.addAttribute("risks", risks);
        
        // 计算各种风险统计数据
        int unsolvedCount = (int) risks.stream()
                .filter(r -> r.getStatus() != 5 && r.getStatus() != 6)
                .count();
        int solvedCount = (int) risks.stream()
                .filter(r -> r.getStatus() == 5)
                .count();
        int highPriorityCount = (int) risks.stream()
                .filter(r -> r.getLevel() >= 3)
                .count();
        
        // 添加风险类型统计
        int type1Count = (int) risks.stream().filter(r -> r.getType() == 1).count();
        int type2Count = (int) risks.stream().filter(r -> r.getType() == 2).count();
        int type3Count = (int) risks.stream().filter(r -> r.getType() == 3).count();
        int type4Count = (int) risks.stream().filter(r -> r.getType() == 4).count();
        int type5Count = (int) risks.stream().filter(r -> r.getType() == 5).count();
        
        // 添加风险状态统计
        int status1Count = (int) risks.stream().filter(r -> r.getStatus() == 1).count();
        int status2Count = (int) risks.stream().filter(r -> r.getStatus() == 2).count();
        int status3Count = (int) risks.stream().filter(r -> r.getStatus() == 3).count();
        int status4Count = (int) risks.stream().filter(r -> r.getStatus() == 4).count();
        int status5Count = (int) risks.stream().filter(r -> r.getStatus() == 5).count();
        int status6Count = (int) risks.stream().filter(r -> r.getStatus() == 6).count();
        
        model.addAttribute("unsolvedCount", unsolvedCount);
        model.addAttribute("solvedCount", solvedCount);
        model.addAttribute("highPriorityCount", highPriorityCount);
        
        // 添加风险类型统计到模型
        model.addAttribute("type1Count", type1Count);
        model.addAttribute("type2Count", type2Count);
        model.addAttribute("type3Count", type3Count);
        model.addAttribute("type4Count", type4Count);
        model.addAttribute("type5Count", type5Count);
        
        // 添加风险状态统计到模型
        model.addAttribute("status1Count", status1Count);
        model.addAttribute("status2Count", status2Count);
        model.addAttribute("status3Count", status3Count);
        model.addAttribute("status4Count", status4Count);
        model.addAttribute("status5Count", status5Count);
        model.addAttribute("status6Count", status6Count);
        
        // 总数据
        model.addAttribute("totalRisks", risks.size());
        model.addAttribute("openRisks", unsolvedCount);
        model.addAttribute("resolvedRisks", solvedCount);
        
        return "risk/list";
    }

    /**
     * 项目风险列表页面
     */
    @GetMapping("/project/{projectId}")
    public String projectRisks(@PathVariable Long projectId, Model model) {
        Project project = projectService.getProjectById(projectId);
        if (project == null) {
            return "redirect:/project/list";
        }
        
        List<Risk> risks = riskService.getRisksByProjectId(projectId);
        
        // 为每个风险添加项目名称和责任人名称，并计算优先级
        for (Risk risk : risks) {
            // 设置项目名称 - 已知项目
            risk.setProjectName(project.getName());
            
            // 添加责任人名称
            if (risk.getOwnerId() != null) {
                User owner = userService.getUserById(risk.getOwnerId());
                if (owner != null) {
                    risk.setOwnerName(owner.getRealName());
                }
            }
            
            // 计算并设置优先级 (基于可能性和影响程度)
            calculateAndSetPriority(risk);
        }
        
        model.addAttribute("project", project);
        model.addAttribute("risks", risks);
        
        // 计算各种风险统计数据
        int unsolvedCount = (int) risks.stream()
                .filter(r -> r.getStatus() != 5 && r.getStatus() != 6)
                .count();
        int solvedCount = (int) risks.stream()
                .filter(r -> r.getStatus() == 5)
                .count();
        int highPriorityCount = (int) risks.stream()
                .filter(r -> r.getPriority() != null && r.getPriority() >= 4)
                .count();
        
        model.addAttribute("unsolvedCount", unsolvedCount);
        model.addAttribute("solvedCount", solvedCount);
        model.addAttribute("highPriorityCount", highPriorityCount);
        
        return "risk/project";
    }

    /**
     * 我负责的风险列表页面 - 使用Spring Security获取当前用户
     */
    @GetMapping("/my")
    public String myRisks(@AuthenticationPrincipal UserDetails userDetails, Model model) {
        // 验证用户
        if (userDetails == null) {
            return "redirect:/risk/list";
        }
        
        User user = userService.getUserByUsername(userDetails.getUsername());
        if (user == null) {
            return "redirect:/risk/list";
        }
        
        List<Risk> risks = riskService.getRisksByOwnerId(user.getId());
        
        // 为每个风险添加项目名称和责任人名称
        for (Risk risk : risks) {
            // 添加项目名称
            if (risk.getProjectId() != null) {
                Project project = projectService.getProjectById(risk.getProjectId());
                if (project != null) {
                    risk.setProjectName(project.getName());
                }
            }
            
            // 设置责任人名称 - 已知责任人就是当前用户
            risk.setOwnerName(user.getRealName());
            
            // 计算并设置优先级
            calculateAndSetPriority(risk);
        }
        
        model.addAttribute("risks", risks);
        
        // 计算各种状态的风险数量
        int status1Count = (int) risks.stream().filter(r -> r.getStatus() == 1).count();
        int status2Count = (int) risks.stream().filter(r -> r.getStatus() == 2).count();
        int status3Count = (int) risks.stream().filter(r -> r.getStatus() == 3).count();
        int status4Count = (int) risks.stream().filter(r -> r.getStatus() == 4).count();
        int status5Count = (int) risks.stream().filter(r -> r.getStatus() == 5).count();
        int status6Count = (int) risks.stream().filter(r -> r.getStatus() == 6).count();
        
        model.addAttribute("status1Count", status1Count);
        model.addAttribute("status2Count", status2Count);
        model.addAttribute("status3Count", status3Count);
        model.addAttribute("status4Count", status4Count);
        model.addAttribute("status5Count", status5Count);
        model.addAttribute("status6Count", status6Count);
        
        return "risk/my";
    }

    /**
     * 风险详情页面
     */
    @GetMapping("/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Risk risk = riskService.getRiskById(id);
        if (risk == null) {
            return "redirect:/risk/list";
        }
        
        // 计算并设置优先级
        calculateAndSetPriority(risk);
        
        model.addAttribute("risk", risk);
        
        // 获取项目信息
        Project project = projectService.getProjectById(risk.getProjectId());
        model.addAttribute("project", project);
        
        // 获取提出人和责任人信息
        User proposer = userService.getUserById(risk.getProposerId());
        model.addAttribute("proposer", proposer);
        
        if (risk.getOwnerId() != null) {
            User owner = userService.getUserById(risk.getOwnerId());
            model.addAttribute("owner", owner);
        }
        
        // 获取所有用户（用于分配责任人）
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        
        return "risk/detail";
    }

    /**
     * 新增风险页面
     */
    @GetMapping("/add")
    public String add(@RequestParam(required = false) Long projectId, Model model) {
        if (projectId != null) {
            Project project = projectService.getProjectById(projectId);
            model.addAttribute("project", project);
        }
        
        // 获取所有项目
        List<Project> projects = projectService.getAllProjects();
        model.addAttribute("projects", projects);
        
        // 获取所有用户（作为责任人候选）
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        
        return "risk/add";
    }

    /**
     * 新增风险 - 使用Spring Security获取当前用户
     */
    @PostMapping("/add")
    @ResponseBody
    public Result<Void> add(@RequestBody Risk risk, @AuthenticationPrincipal UserDetails userDetails) {
        // 验证用户
        if (userDetails == null) {
            return Result.error("未登录或登录已过期");
        }
        
        // 设置提出人为当前用户
        User user = userService.getUserByUsername(userDetails.getUsername());
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        risk.setProposerId(user.getId());
        
        boolean success = riskService.addRisk(risk);
        if (success) {
            return Result.success();
        } else {
            return Result.error("添加风险失败");
        }
    }

    /**
     * 编辑风险页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        Risk risk = riskService.getRiskById(id);
        if (risk == null) {
            return "redirect:/risk/list";
        }
        
        model.addAttribute("risk", risk);
        
        // 获取项目信息
        Project project = projectService.getProjectById(risk.getProjectId());
        model.addAttribute("project", project);
        
        // 获取所有用户（作为责任人候选）
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        
        return "risk/edit";
    }

    /**
     * 编辑风险
     */
    @PostMapping("/edit")
    @ResponseBody
    public Result<Void> edit(@RequestBody Risk risk) {
        boolean success = riskService.updateRisk(risk);
        if (success) {
            return Result.success();
        } else {
            return Result.error("更新风险失败");
        }
    }

    /**
     * 删除风险
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        boolean success = riskService.deleteRisk(id);
        if (success) {
            return Result.success();
        } else {
            return Result.error("删除风险失败");
        }
    }

    /**
     * 更新风险状态
     */
    @PostMapping("/status/{id}/{status}")
    @ResponseBody
    public Result<Void> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        boolean success = riskService.updateRiskStatus(id, status);
        if (success) {
            return Result.success();
        } else {
            return Result.error("更新风险状态失败");
        }
    }

    /**
     * 分配风险责任人
     */
    @PostMapping("/assign/{id}/{ownerId}")
    @ResponseBody
    public Result<Void> assignOwner(@PathVariable Long id, @PathVariable Long ownerId) {
        boolean success = riskService.updateRiskOwner(id, ownerId);
        if (success) {
            return Result.success();
        } else {
            return Result.error("分配风险责任人失败");
        }
    }

    /**
     * 计算并设置风险优先级
     */
    private void calculateAndSetPriority(Risk risk) {
        if (risk.getProbability() == null || risk.getImpact() == null) {
            risk.setPriority(1); // 默认为很低
            return;
        }
        
        int probability = risk.getProbability();
        int impact = risk.getImpact();
        int priority;
        
        // 简单的优先级计算逻辑
        if (probability >= 3 && impact >= 3) {
            priority = 5; // 很高
        } else if ((probability >= 3 && impact >= 2) || (probability >= 2 && impact >= 3)) {
            priority = 4; // 高
        } else if (probability >= 2 && impact >= 2) {
            priority = 3; // 中
        } else if (probability >= 2 || impact >= 2) {
            priority = 2; // 低
        } else {
            priority = 1; // 很低
        }
        
        risk.setPriority(priority);
    }
} 